<template>

  <div class="app-container">

    <h2 style="text-align: center;">发布新课程</h2>

    <el-steps :active="1" process-status="wait" align-center style="margin-bottom: 40px;">
      <el-step title="编辑课程基本信息"/>
      <el-step title="编辑课程大纲"/>
      <el-step title="课程最终发布"/>
    </el-steps>

    <el-form label-width="120px">

        <el-form-item label="课程标题">
            <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"/>
        </el-form-item>

        <!-- 所属分类：二级联动下拉列表 -->
        <el-form-item label="所属分类">
          <!-- 一级分类 -->
          <el-select v-model="courseInfo.subjectParentId" @change="SubjectOneToTwo" placeholder="请选择一级课程分类">
            <el-option 
              v-for="subjectOne in subjectOneList"
              :key="subjectOne.id"
              :label="subjectOne.title"
              :value="subjectOne.id"/>
          </el-select>
          <!-- 二级分类 -->
          <el-select v-model="courseInfo.subjectId" placeholder="请选择二级课程分类">
            <el-option 
              v-for="subjectTwo in subjectTwoList"
              :key="subjectTwo.id"
              :label="subjectTwo.title"
              :value="subjectTwo.id"/>
          </el-select>
        </el-form-item>

        <!-- 课程讲师 -->
        <el-form-item label="课程讲师">
          <el-select v-model="courseInfo.teacherId" placeholder="请选择讲师">
            <el-option 
              v-for="teacher in teacherList"
              :key="teacher.id"
              :label="teacher.name"
              :value="teacher.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="总课时">
            <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数"/>
        </el-form-item>

        <!-- 课程简介-->
        <el-form-item label="课程简介">
            <tinymce :height="300" v-model="courseInfo.description"/>
        </el-form-item>

        <!-- 课程封面-->
        <el-form-item label="课程封面">
          <el-upload
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :action="BASE_API+'/ossservice/fileoss'"
            class="avatar-uploader">
            <img :src="courseInfo.cover">
          </el-upload>
        </el-form-item>

        <el-form-item label="课程价格">
            <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元"/> 元
        </el-form-item>

        <div class="el-form-item-my">
            <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存并下一步</el-button>
        </div>
    </el-form>
  </div>
</template>
<script>
import course from '@/api/edu/course'
import teacher from '@/api/edu/teacher'
import subject from '@/api/edu/subject'
import Tinymce from '@/components/Tinymce'

export default {
  components: { Tinymce },// 定义Tinymce
  data() {
    return {
        courseInfo: {
            title: '',
            subjectParentId: '',// 一级分类Id
            subjectId: '',// 二级分类Id
            teacherId: '',
            lessonNum: 0,
            description: '',
            cover: 'https://jiyue-edu.oss-cn-shenzhen.aliyuncs.com/2020/05/13/2b5275408e9a48848b1c455ce327e1abfile.png',
            price: 0,
        },
        BASE_API: process.env.BASE_API,// 接口API地址
        teacherList: [],// 所有讲师
        subjectOneList: [],// 一级课程分类
        subjectTwoList: [],// 二级课程分类
        saveBtnDisabled: false // 保存按钮是否禁用
    }
  },

  created() {
    this.init()
  },
  watch: {// 监听事件
    $route(to, from) {// 路由变化方式，路由发生变化，方法就会执行
      this.init();
    }
  },

  methods: {

    // 初始化方法
    init() {
      if(this.$route.params && this.$route.params.id) {
        const courseId = this.$route.params.id;
        // 说明有参数，执行回显方法
        this.queryCourseInfoByCourseId(courseId)
      } else {
        // 清空对象
        this.courseInfo = {
          title: '',
          subjectParentId: '',// 一级分类Id
          subjectId: '',// 二级分类Id
          teacherId: '',
          lessonNum: 0,
          description: '',
          cover: 'https://jiyue-edu.oss-cn-shenzhen.aliyuncs.com/2020/05/13/2b5275408e9a48848b1c455ce327e1abfile.png',
          price: 0,
        }
        // 初始化所有讲师
        this.queryTeacherList()
        // 初始化一级分类
        this.queryAllSubject()
      }
    },

    // 根据课程id查询课程基本信息（回显）
    queryCourseInfoByCourseId(courseId) {
      course.queryCourseInfoByCourseId(courseId)
        .then(response => {
          this.courseInfo = response.data.courseInfoVo
          // 查询所有的一级和二级分类
          subject.queryAllSubject()
            .then(response => {
              // 获取所有的一级分类
              this.subjectOneList = response.data.items
              // 遍历所有的一级分类
              for (let x = 0; x < this.subjectOneList.length; x++) {
                const oneSubject = this.subjectOneList[x];
                // 根据回显的一级分类和所有的一级分类进行对比
                if(oneSubject.id === this.courseInfo.subjectParentId) {
                  // 获取所有的二级分类
                  this.subjectTwoList = oneSubject.children
                }
              }
              
            })
            // 初始化所有讲师
            this.queryTeacherList()
        })
    },

    // 根据课程id修改课程基本信息
    updateCourseInfoByCourseId() {
      course.updateCourseInfoByCourseId(this.courseInfo)
        .then(response => {
          this.$message({
            type: 'success',
            message: '课程更新成功'
          })
          this.$router.push({path: '/course/chapter/'+this.$route.params.id})
        })
    },

    // 课程封面-上传成功
    handleAvatarSuccess(res, file) {
      console.log(res)// 上传相应
      console.log(URL.createObjectURL(file.raw))// base64编码
      this.courseInfo.cover = res.data.url
    },

    // 课程封面-上传成功后
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if(!isJPG) {
        this.$message.error('上传封面图片只能是 JPG 格式！')
      }
      if(!isLt2M) {
        this.$message.error('上传封面图片大小不能超过2MB')
      }
      return isJPG && isLt2M
    },

    // 触发事件，通过一级分类查询二级分类
    SubjectOneToTwo(value) {
      for (let i = 0; i < this.subjectOneList.length; i++) {
        // 判断是否同一个副Id
        if(value === this.subjectOneList[i].id) {
          this.subjectTwoList = this.subjectOneList[i].children
          // 清空二级分类的值
          this.courseInfo.subjectId = ''
        }
      }
    },

    // 查询一级分类
    queryAllSubject() {
      subject.queryAllSubject()
        .then(response => {
          this.subjectOneList = response.data.items
        })
    },

    // 查询所有讲师
    queryTeacherList() {
      teacher.queryTeacherList()
        .then(response => {
          this.teacherList = response.data.teachers
        })
    },

    // 保存并下一步
    saveOrUpdate() {
      
        // 判断是否更新
      if (this.$route.params && this.$route.params.id) {
        this.updateCourseInfoByCourseId()
      } else {
        course.queryCourseInfo(this.courseInfo)
        .then(response => {
            this.$message({
                type: 'success',
                message: '课程保存成功'
            })
            this.$router.push({ path: '/course/chapter/'+response.data.courseId })
        })
      }
    },
    
  }
}
</script>

<style scoped>
.tinymce-container {
  line-height: 29px;
}
.el-form-item-my {
    width: 183px;
    margin: 0 auto;
}
</style>